<template>
  <div class="hdgl-edit-step-1">
    <a-form-model
      ref="form"
      :model="model"
      :rules="rules"
      labelAlign="right"
      :label-col="labelCol"
      :wrapper-col="wrapperCol">
      <a-form-model-item label="活动名称" :required="true">
        <a-input
          class="ml-30"
          v-model="model.name"
          placeholder="请输入不超过16个字的活动名称"
          :maxLength="16"
          :suffix="model.name.length+'/16'"
          style="max-width: 370px"/>
      </a-form-model-item>
      <a-form-model-item label="触发关键字" :required="true">
        <a-input
          class="ml-30"
          v-model="model.triggerKeyword"
          placeholder="请输入不超过8个字的触发关键字"
          :maxLength="8"
          :suffix="model.triggerKeyword.length+'/8'"
          style="max-width: 370px"/>
        <wx-reply-editor-wrap
          class="ml-30"
          v-model="model.msgKeywordReply"
          title="关键词回复规则文案"
          :menus="['user', 'team', 'pushpin', 'contacts', 'link']"
          tips="当用户发送关键词，推送此规则文案给用户"
          sampleCopyType="keywordReply"/>
      </a-form-model-item>
      <a-form-model-item label="结束时间" :required="true">
        <a-date-picker
          class="ml-30"
          v-model="endTime"
          @change="changeEndTime"
          show-time
          style="max-width: 370px"
          format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择时间"/>
      </a-form-model-item>
      <a-form-model-item label="参与公众号" :required="true">
        <div class="ml-30 d-aic">
          <div class="mp-item-list">
            <div
              class="mp-item-list-content d-aic"
              v-for="(item,index) in model.mps"
              :key="index"
              :class="{active:item.select}">
              <img class="mp-list-avatar" :src="item.avatar"><span
                class="mp-list-name">{{ item.mpName }}</span>
              <img v-if="item.select" class="mp-list-select" src="../../../../../perm/assets/select.png">
            </div>
          </div>
          <b-button
            type="default"
            ghost="default"
            btnContent="修改"
            style="width: 88px"
            @click="showGzh=true"/>
        </div>
        <wx-reply-editor-wrap
          class="ml-30"
          v-model="model.msgGuideQw"
          title="活动引导文案"
          :menus="['user', 'pushpin', 'contacts', 'link']"
          tips="用户关注公众号后，推送此文案和客服名片"
          sampleCopyType="guide"/>
      </a-form-model-item>
      <a-form-model-item label="裂变成员" :required="true">
        <div class="d-aic ml-30">
          <a-select
            show-search
            mode="multiple"
            :value="selectMembers"
            placeholder="请选择裂变成员"
            notFoundContent="没有添加可用裂变成员，请在成员管理添加"
            style="width: 362px;"
            :dropdownStyle="{height:'auto'}"
            :dropdownMenuStyle="{height:'auto'}"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            @select="memberChange"
            @search="handleSearch"
            @deselect="memberDeselect"
          >
            <a-select-option v-for="(item,index) in memberList" :key="index">
              <img class="member-list-avatar" :src="item.avatar"><span class="member-list-name">{{ item.name }}</span>
            </a-select-option>
          </a-select>
          <div v-if="!memberList.length" style="white-space: nowrap" class="ml-30">
              没有裂变成员可供添加，请在<a style="color: #0c8eff" href="#/qywx/jcgn/member">裂变成员管理</a>添加
          </div>
        </div>
      </a-form-model-item>

    </a-form-model>
    <a-modal v-model="showGzh" :title="null" :footer="null" width="640px">
      <div class="modal-class-title">
        公众号
      </div>
      <div class="mp-list-wrap">
        <div v-if="!mpList.length">
          <a-empty/>
          <div class="d-jcc-aic">
            <a href="#/qywx/jcgn/gzh">绑定公众号</a>
          </div>
        </div>
        <div
          class="d-jcs-aic mp-list"
          v-for="mp in mpList"
          :key="mp.id"
          :class="{active:mp.select}"
          @click="selectChange(mp)">
          <div><img class="mp-list-avatar" :src="mp.avatar"><span class="mp-list-name">{{ mp.mpName }}</span>
          </div>
          <div class="d-aic mp-list-right">
            <div class="mp-type">
              {{ getServiceType(mp.serviceTypeInfo) }}
            </div>
            <div class="mp-verify-type d-jcc-aic">
              {{ getVerifyType(mp.verifyTypeInfo).substring(0,6) }}
            </div>
          </div>
          <img v-if="mp.select" class="mp-list-select" src="../../../../../perm/assets/select.png">
        </div>
      </div>
      <div class="d-aic" style="justify-content: flex-end;">
        <b-button key="submit" type="primary" @click="saveMp" btnContent="确定"/>
      </div>
    </a-modal>
    <a-modal
      class="tag-modal"
      v-model="showMember"
      title="提示"
      width="640px"
      @ok="gotoMember"
      @cancel="showMember=false">
      <div style="white-space: nowrap" class="ml-30">
        没有裂变成员可供添加，,无法创建活动，请先前往<a style="color: #0c8eff" href="#/qywx/jcgn/member">裂变成员管理</a>添加
      </div>
    </a-modal>
  </div>
</template>

<script>
    import WxReplyEditor from './wx-reply-editor'
    import BButton from '@/perm/components/b-button'
    import API from '@/api/common'
    import WxReplyEditorWrap from './wx-reply-editor-wrap'
    import moment from 'moment'

    export default {
        name: 'HdglEditStep1',
        components: { WxReplyEditorWrap, BButton, WxReplyEditor },
        props: {
            model: {
                type: Object,
                default: () => {
                }
            }
        },
        data () {
            return {
                labelCol: { span: 2 },
                wrapperCol: { span: 14 },
                showGzh: false,
                showMember: false,
                rules: {
                    name: [
                        { required: true, message: '请输入活动名称', trigger: 'blur' }
                    ],
                    endTime: [
                        { required: true, message: '请输入活动结束时间', trigger: 'blur' }
                    ],
                    triggerKeyword: [
                        { required: true, message: '请输入触发关键字', trigger: 'blur' }
                    ]
                },
                mpList: [],
                originalMemberList: [],
                memberList: [],
                // 存的是memberList的下标
                selectMembers: [],
                serviceTypeList: ['订阅号', '企业号', '服务号'],
                verifyTypeList: ['未认证', '微信认证', '新浪微博认证', '腾讯微博认证', '已资质认证通过但还未通过名称认证', '已资质认证通过、还未通过名称认证，但通过了新浪微博认证', '已资质认证通过、还未通过名称认证，但通过了腾讯微博认证'],
                keywordDemo: false,
                endTime: null
            }
        },
        computed: {
            qwUserId () {
                return this.$store.state.user.info.qwUserId
            }
        },
        mounted () {
            this.initTime()
            this.getMpList()
            this.getMemberList()
        },
        methods: {
            selectChange (mp) {
                // 先把不是自己的所有的都设为false
                this.mpList.forEach(item => {
                    if (item.mpId !== mp.mpId) {
                        item.select = false
                    }
                })
                mp.select = !mp.select
            },
            initTime () {
                const time = this.$Utils.getTimeFormat(this.model.endTime)
                this.endTime = this.model.endTime ? moment(time, 'YYYY-MM-DD HH:mm:ss') : ''
            },
            memberDeselect (data) {
                const index = this.selectMembers.indexOf(data)
                this.selectMembers.splice(index, 1)
            },
            memberChange (data) {
                this.selectMembers.push(data)
            },
            changeEndTime (data, dataString) {
                this.model.endTime = new Date(dataString.replace(/-/g, '/')).getTime()
                this.endTime = data
            },
            handleSearch (data) {
                this.memberList = this.originalMemberList.filter(item => item.name.indexOf(data) >= 0)
            },
            /**
             * 获取裂变成员列表
             */
            getMemberList () {
                API.listActive({ qwUserId: this.qwUserId }).then(res => {
                    if (!res.length) {
                        this.showMember = true
                    }
                    // 原始数据
                    this.originalMemberList = res
                    this.memberList = res

                    // 初始化选择的裂变成员
                    const membersFromData = this.model.members || []
                    this.selectMembers = []
                    membersFromData.forEach(item => {
                        const index = this.memberList.findIndex(member => member.id === item.qwMemberId)
                        if (index >= 0) {
                            this.selectMembers.push(index)
                        }
                    })
                }).catch()
            },
            /**
             * 清理无效成员
             */
            clearNullMember () {
                // 暂时清空model中的裂变成员数据, 转为未转换的选择器数据
                this.model.members = []
            },
            /**
             * 获取个人账户下的公众号列表
             */
            getMpList () {
                API.listMyMps().then(res => {
                    res = res.map(item => {
                        return {
                            ...item,
                            select: false
                        }
                    })
                    this.model.mps.forEach(item => {
                        res.forEach(mp => {
                            if (mp.mpAppId === item.mpAppId) {
                                mp.select = true
                                item.select = true
                            }
                        })
                    })
                    this.mpList = res
                }).catch()
            },
            getServiceType (type) {
                if (!type) {
                    return ''
                }
                const index = Number.parseInt(type)
                return this.serviceTypeList[index]
            },
            getVerifyType (type) {
                if (!type) {
                    return ''
                }
                const index = Number.parseInt(type)
                return this.verifyTypeList[index + 1]
            },
            gotoMember () {
                this.$router.push({ path: '/qywx/jcgn/member"' })
            },
            saveMp () {
                this.model.mps = []
                this.mpList.forEach(item => {
                    if (item.select) {
                        this.model.mps.push(item)
                    }
                })
                if (!this.model.mps.length) {
                    this.$message.error(`请选择公众号`)
                    return
                }
                this.showGzh = false
            },
            check () {
                if (this.model.name.trim().length === 0) {
                    throw new Error('请输入活动名')
                }
                if (this.model.triggerKeyword.trim().length === 0) {
                    throw new Error('请输入关键字')
                }
                const rules = this.model.rules
                this.$refs['form'].validate((valid, errObj) => {
                    if (!valid) {
                        const message = errObj[Object.keys(errObj)[0]][0].message
                        throw new Error(message)
                    } else if (rules.length === 0) {
                        throw new Error('活动阶梯最少1阶')
                    } else if (rules[0].target <= 0) {
                        throw new Error('活动助力人数最少1人')
                    } else if (rules[0].stock <= 0) {
                        throw new Error('活动助力奖品最少1份')
                    }
                })
                // 检查完成后处理数据格式
                this.beforeSave()
            },
            beforeSave () {
                // 成员列表数据
                this.preMember()
            },
            preMember () {
                this.model.members = this.selectMembers.map(item => {
                    const member = this.memberList[item]
                    return {
                        gameTaskId: this.model.id || null,
                        qwMemberId: member.id,
                        userId: member.userId,
                        name: member.name
                    }
                })
            }
        }
    }
</script>

<style scoped lang="less">

    .mp-list-select {
        position: absolute;
        right: 0;
        bottom: 0;
        width: 18px;
        height: 18px;
    }

    .mp-list-wrap {
        margin-bottom: 20px;

        .mp-list {
            position: relative;
            padding: 0 13px;
            width: 588px;
            height: 64px;
            border: 1px solid #D9D9D9;

            &.active {
                border: 1px solid #1890FF;
            }

            .mp-list-right {
                .mp-type {
                    margin-right: 14px;
                    color: #2493FC;
                }

                .mp-verify-type {
                    padding: 0 13px;
                    max-width: 120px;
                    height: 24px;
                    border-radius: 4px;
                    background-color: rgba(229, 247, 255, 100);
                    color: rgba(24, 144, 255, 100);
                    font-size: 14px;
                    border: 1px solid rgba(165, 214, 255, 100);
                    overflow: hidden;
                }
            }
        }

        .mp-list + .mp-list {
            margin-top: 10px;
        }
    }

    .mp-list-avatar {
        margin-right: 6px;
        width: 42px;
        height: 42px;
        border-radius: 50%;
    }

    .mp-list-name {
        font-size: 14px;
        color: #595959;
    }

    .member-list-avatar {
        margin-right: 6px;
        width: 15px;
        height: 15px;
        border-radius: 50%;
    }

    .member-list-name {
        font-size: 14px;
        color: #595959;
    }

    .mp-item-list {
        display: flex;
        flex-wrap: wrap;
        max-width: 490px;

        .mp-item-list-content {
            position: relative;
            margin-right: 15px;
            margin-bottom: 10px;
            padding: 0 13px;
            width: 148px;
            height: 64px;
            border: 1px solid #D9D9D9;

            &.active {
                border: 1px solid #1890FF;
            }
        }

    }

    .modal-class-title {
        padding-bottom: 22px;
        font-size: 20px;
        color: #262626;
    }

    .hdgl-edit-step-1 {
        .award-item {
            margin-bottom: 4px;
            font-size: 14px;
            color: #595959;
        }

        .award-button {
            width: 100px;
            height: 32px;
            color: #8C8C8C;
        }

        .ml-30 {
            margin-left: 30px;
        }
    }
</style>
